package cn.yunbamboos.rest.service.dto;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjUtil;
import cn.yunbamboos.Model;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;

import java.util.List;

public class Data {

    private final JSONObject json;

    /**
     * 返回数据包
     */
    public Data() {
        this.json = new JSONObject();
    }

    public JSONObject encode() {
        return json;
    }

    public boolean isEmpty(){
        return this.json.isEmpty();
    }

    /**
     * 添加自定义返回数据包
     *
     * @param key   自定义属性key
     * @param value 自定义属性值
     */
    public void set(String key, Object value) {
        if (ObjUtil.isNotNull(value)) {
            this.json.put(key, value);
        }
    }

    public void setModelList(String key, List<? extends Model> list) {
        JSONArray array = new JSONArray();
        if (CollectionUtil.isNotEmpty(list)) {
            for (Model model : list) {
                array.add(model.encode());
            }
        }
        this.json.put(key, array);
    }

    public void setModel(String key, Model model) {
        if (ObjUtil.isNotNull(model)) {
            this.json.put(key, model.encode());
        }
    }
}
